package com.ciaojian.client.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ciaojian.core.model.HaircutService;
import com.ciaojian.core.model.Member;
import com.ciaojian.core.service.MemberService;
import com.ciaojian.pay.unionpay.LogUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Atlakyn
 */
@Service
public class MemberServiceImpl extends MemberService {

    /**
     * 获取折扣
     * <p>根据服务类型来获取这类服务的优惠折扣</p>
     *
     * @param title 服务标题
     */
    public Map<String, String> getMemberDiscount(String title) {
        LambdaQueryWrapper<HaircutService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(HaircutService::getTitle, title);
        // 服务类型
        HaircutService haircutService = new HaircutService().selectOne(lambdaQueryWrapper);
        Assert.notNull(haircutService, "服务类型有误");
        // 服务名称
        String serviceType = haircutService.getType().getDescription();
        // 会员类型列表,遍历会员类型列表查对应服务类型的折扣
        List<Member> memberList = new Member().selectAll();
        ObjectMapper om = new ObjectMapper();
        Map<String, String> result = new HashMap<>(memberList.size());
        memberList.forEach(member -> {
            try {
                Map map = om.readValue(member.getDiscount(), Map.class);
                // 获取折扣
                String discount = MapUtil.getStr(map, serviceType);
                result.put(member.getTitle(), discount);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                LogUtil.writeErrorLog(e.getMessage(), e);
            }
        });
        return result;
    }

    /**
     * 查找用户会员卡
     *
     * @param userId 用户ID
     * @param title  服务名称
     * @return 用户的会员卡列表 or
     * @throws JsonProcessingException json进程异常
     */
    public Object getMemberByUser(Integer userId, String title) throws JsonProcessingException {
        List<Map<String, Object>> memberList = baseMapper.findUserMemberCard(userId);
        // 没传标题或者会员列表为空就返回一个会员列表
        if (StrUtil.isBlank(title) || CollUtil.isEmpty(memberList)) {
            return memberList;
        } else {
            LambdaQueryWrapper<HaircutService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HaircutService::getTitle, title);
            HaircutService haircutService = new HaircutService().selectOne(lambdaQueryWrapper);
            return getDiscountByType((Integer) memberList.get(memberList.size() - 1).get("id"), haircutService.getType());
        }
    }
}
